<?php

/**
 * Контроллер отправки почты
 */
class Mailer implements iMailer {

	private static $oEngine = null;
	private static $sFromAddress = '';
	private static $sFromName = '';
	private static $bDelay = true;
	
	/**
	 * Конструктор
	 * @return void
	 */
	private function __construct () {}
	
	/**
	 * Отправить письмо
	 * @param EMail $oEMail письмо
	 * @param boolean $bForce отправить без очереди
	 * @return boolean
	 */
	public static function sendEMail (EMail $oEMail, $bForce = false) {
		if (self::$oEngine === null) {
			self::init ();
		}
	
		$address = $oEMail->getAddress ();
		$body =	$oEMail->getBody ();
		$subject = $oEMail->getSubject ();
		
		if ($address && $body && $subject) {
			if (self::$bDelay && !$bForce) {
				$object = new Object (TypesController::getInstance()->getTypeByName ('email'));
				$object->setValue ('address', $address);
				$object->setValue ('body', $body);
				$object->setValue ('subject', $subject);
				$object->createNew ();
				
				return true;
			} else {
				if (self::$oEngine->send ($address, $subject, $body, self::$sFromAddress, self::$sFromName)) {
					return true;
				} else {
					$object = new Object (TypesController::getInstance()->getTypeByName ('email'));
					$object->setValue ('address', $address);
					$object->setValue ('body', $body);
					$object->setValue ('subject', $subject);
					$object->createNew ();
					
					return false;
				}
			}
		}
		
		return false;
	}
	
	public static function sendEMails (array $aEMails, $bForce = false) {
		foreach ($aEMails as $oEmail) {
			if ($oEMail instanceof EMail) {
				self::sendEMail ($oEmail, $bForce);
			}
		}
	}
	
	private function init () {
		if (!defined ('MAILER')) {
			throw new CoreException ('Backend for mail not defined!');
		}
		
		$backendFile = ENGINE_ROOT . '/classes/Mailer/backend/' . MAILER . '.php';
		
		if (!file_exists ($backendFile)) {
			throw new CoreException ('Backend "' . MAILER . '" for mail not found!');
		}
		
		include ENGINE_ROOT . '/classes/Mailer/backend/iMailerBackend.php';
		include $backendFile;
		
		$className = 'mailer_backend_' . MAILER;
		
		if (!class_exists ($className)) {
			throw new CoreException ('Class "' . $className . '" not found!');
		}
		
		self::$oEngine = new $className;
		
		self::$sFromAddress = Regedit::getInstance()->get ('//settings/site/mail/from_address');
		self::$sFromName = Regedit::getInstance()->get ('//settings/site/mail/from_name');
		self::$bDelay = (bool) Regedit::getInstance()->get ('//settings/site/mail/delay');
	}
}